<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
			
%>
<%@ include file="../../commons/taglibs.jsp"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>列表</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
			<script type="text/javascript" src="<%=path %>/js/jquery-form.js"></script>
			<script language="javascript" src="<%=path %>/jsp/OutOrder/LodopFuncs.js"></script>
		
	<script language="javascript" src="LodopFuncs.js"></script>
		<object id="LODOP_OB" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width=0 height=0> 
			<embed id="LODOP_EM" type="application/x-print-lodop" width=0 height=0 pluginspage="install_lodop32.exe"></embed>
		</object> 
		
		
<script type="text/javascript">
		
		var spinerArr = new Array();
		var spinerPriceArr  = new Array();
		
		/**重写JS-remove方法***/
		Array.prototype.remove=function(dx) 
		{ 	
		    if(isNaN(dx)||dx>this.length){return false;} 
		    for(var i=0,n=0;i<this.length;i++) 
		    { 
		        if(this[i]!=this[dx]) 
		        { 
		            this[n++]=this[i]; 
		        } 
		    } 
		    this.length-=1;
		};
			
			function onClickCell(index, field, value) {
				if(field!='num'){
					confirmDetail();
				}
			}

			var editIndex = undefined;
			function endEditing() {
				if (editIndex == undefined) {
					return true
				}
				if ($('#tt2').datagrid('validateRow', editIndex)) {
					$('#tt2').datagrid('endEdit', editIndex);
					editIndex = undefined;
					return true;
				} else {
					return false;
				}
			}
			
			function loadDetail(){
				var url="<%=path %>/jsp/OutOrder/orderChoese.jsp"	
				$('#goodChoeseDiv').dialog('refresh', url);
		 		$('#goodChoeseDiv').dialog('open'); 
			}
			
			function confirmDetail(){
				var all;
				all = $("#tt2").datagrid("getData");
				for(var i=0;i<all.rows.length;i++){
					var pre_value = $("#"+spinerArr[i]).val();
					var price=$("#"+spinerPriceArr[i]).val();
					//计算每行金额
					var sum = parseInt(price)*parseInt($("#"+spinerArr[i]).val());
					sum = sum.toFixed(2);
					//更新每行金额
					$('#tt2').datagrid('updateRow',{
						index: i,
						row: {
							price:"<input id='"+spinerPriceArr[i]+"' value='"+price+"' style='width:80px;' required='required'>",
							num:"<input id='"+spinerArr[i]+"' value='"+pre_value+"' style='width:80px;' required='required'>",
							sum: sum
						}
					});
					
					//添加微调器
               		$("#"+spinerArr[i]).numberspinner({
							min: 0,
							max: 99999,
							precision:0,
							editable: true
					});
					
               	//添加微调器
               		$("#"+spinerPriceArr[i]).numberspinner({
							min: 0,
							max: 99999,
							precision:0,
							editable: true
					});
					
					
				}
				//计算总金额
				totalSum();
			}
			
			
			function saveConfirmDetail(){
				var all;
				all = $("#tt2").datagrid("getData");
				for(var i=0;i<all.rows.length;i++){
					var pre_value = $("#"+spinerArr[i]).val();
					var price=$("#"+spinerPriceArr[i]).val();
					//计算每行金额
					var sum = parseInt(price)*parseInt($("#"+spinerArr[i]).val());
					sum = sum.toFixed(2);
					//更新每行金额
					$('#tt2').datagrid('updateRow',{
						index: i,
						row: {
							price:price,
							num:pre_value,
							sum: sum
						}
					});
				}
				//计算总金额
				totalSum();
			}
			

			//计算总金额
			function totalSum(){
				var all;
				all = $("#tt2").datagrid("getData");
				var total=0;
				for(var i=0;i<all.rows.length;i++){
					total+=parseFloat(all.rows[i].sum);
				}
				total = total.toFixed(2);
				
				var discount_fee=$("#discount_fee").val();
				
				$("#order_sum_fee").val(total); //订单总金额
				if(parseFloat(discount_fee)){
					if(parseFloat(discount_fee)<total){
						total=(total-parseFloat(discount_fee)).toFixed(2);
						$("#discount_fee_hid").val(parseFloat(discount_fee)) //折扣金额
					}
				}
				$("#real_sum_fee").val(total); //订单实际金额
				
				//金额大写
				var caps=numToCny(total);
				//设置合计栏信息
				setTotal(total,caps);
			}
			
			/**合计栏**/
			function setTotal(total,caps){
				if('NaN'==total){
					total="0.00";
					caps="零元零角零分";
				}
				$("#tt_totalNum").html(total);
				$("#tt_totalSum").html(caps);
			}
			
			/**统购删除行**/
			function deletRow(index){
				spinerArr.remove(index);
				$('#tt2').datagrid('deleteRow', index);
				confirmDetail();
			}
			
			function addCustom(){
				  //动态搜索  
				 var q=$('#custom_id').combogrid("getText"); 
                $('#custom_id').combogrid("grid").datagrid("reload", { 'q': q });  
               $('#custom_id').combogrid("setValue", q);  
               $('#custom_id').combogrid('showPanel');
				// addDialogTag("<%=path %>/jsp/OutCurstom/form.jsp",'添加客户','<%=path %>/curstom/createOrUpdate','450','420');   
			}
			
			
			$(function(){
				 $('#cus').linkbutton('disable'); 
				$('#custom_id').combogrid({  
					panelWidth:500,  
					panelHeight:400, 
				   	delay: 200,  
				  	mode: 'remote',
				   	pagination:true,
				   	fit: false,
				    rownumbers:true,//序号      
				   	collapsible:false,//是否可折叠的      
				    url:'<%=path %>/curstom/listForSelect',  
			        remoteSort:false,   
			        idField:'id',  
			        textField: 'name' ,
			        singleSelect:false,//是否单选  
			        pagination:true,//分页控件  
			        rownumbers:true,//行号  
			   		 columns:[[
						{field:'name',title:'姓名',width:180,align:'center'},
						{field:'phone',title:'手机号',width:130,align:'center'},
						{field:'address',title:'住址',width:100,align:'center'},
						{field:'create_date',title:'创建时间',width:150,align:'center'}
						
							]],
				     keyHandler: {  
	                           up: function() {},  
	                           down: function() {},  
	                           enter: function() {},  
	                           query: function(q) {  
	                               //动态搜索  
	                               $('#custom_id').combogrid("grid").datagrid("reload", { 'q': q });  
	                              $('#custom_id').combogrid("setValue", q);  
	                           }  
	                       } , 		
			        frozenColumns:[[  
			            {field:'id',checkbox:true}  
			        ]],
				    onSelect: function(record){ 
					    	var g = $('#custom_id').combogrid('grid');	// get datagrid object
						    var r = g.datagrid('getSelected'); 
					    	$("#customName").val(r.name)
					    	$("#custom_phone").val(r.phone);
					    	$("#custom_address").val(r.address);
					    	isShow();
					    	
						}
					}); 
				
			})
			
			function valdate(){
				if($("#customName").val()==''){
					$.messager.alert('提示',"没有客户姓名！", 'error');
					return false;
				}else if($("#custom_phone").val()==''){
					$.messager.alert('提示',"没有填写客户手机号!", 'error');
					return false;
				}else if($("#custom_address").val()==''){
					$.messager.alert('提示',"没有填写客户的住址！", 'error');
					return false;
				}else{
					var all=$("#tt2").datagrid("getData");
					if(all.rows.length==0){
						$.messager.alert('提示',"您还没点单了，请确认以后再提交！", 'error');
						return false
					}else{
						return true
					}
					
				}
			}
			
			/**保存订单**/
			function saveOutOrder(){
				if(valdate()){
					saveConfirmDetail();
					$('#tt2').datagrid('acceptChanges');
					var all=$("#tt2").datagrid("getData");
					
					var jsonDetail = JSON.stringify(all.rows);
					var custom_id=$("#custom_id").combogrid("getValue");
					if(custom_id==''){ //没有找到customid 收银员手动填写的
						$("#customName").val($('#custom_id').combogrid("getText"));//把文本框填写的值赋予客户名称
					}
					$("#menuJson").val(jsonDetail);
					  var form = $("form[name=costForm]");  
				        var options  = {    
				            url:'<%=path%>/order/save',    
				            type:'post',    
				            success:function(data)    
				            {    
			        			if(data=='-1'){
			        				 $.messager.progress('close');
			        				$.messager.alert('提示','订单生成失败！请重新下单');   
			        			}else{
			        				 $.messager.progress('close');
// 			        				 $.messager.progress( {
// 			 			        		msg : '订单打印中......'
// 			 						});
			        				 
			        				 try
			        				 {
			        					 orderPrint($("#customName").val(),all.rows);
			        				 }
			        				 catch (e)
			        				 {
// 			        					 $.messager.progress('close');
			        						$.messager.alert('提示',"打印失败，单据生产成功", 'warning');
			        					 window.parent.closeTab(); //关闭当前页
			        				 } 
			        				
			        				 
		        					setTimeout(function(obj){
// 		        						 $.messager.progress('close');
		        						window.parent.closeTab(); //关闭当前页
		        				   		},2000); 
			        				   
			        				 
			        			}
				            	
			        			
				            }    
				        };    
				        form.ajaxSubmit(options);  
				        $.messager.progress( {
			        		msg : '订单生成中......'
						});
					
				}
				
			}
			
			function isShow(){
				var value=$("#custom_phone").val();
				if(value){
					 $('#cus').linkbutton('enable'); 
				}else{
					 $('#cus').linkbutton('disable'); 
				}
			}
			
			function loadCustom(){
				var phone=$("#custom_phone").val();
				$.ajax( {
					cache : true,
					type : "POST",
					url : '<%=path %>/order/loadCustom',
					data : {
							phone:phone
					},
					async : false,
					error : function(request) {
						$.messager.alert('提示',"操作失败！", 'warning');
					},
					success : function(data) {
						$.messager.alert('信息',"订餐："+data.cnt+"&nbsp;&nbsp;| 退单："+data.tuiCnt+"&nbsp;&nbsp;|总花费："+data.totalFee, 'info!');
				}
			})	
			}
		</script>
	</head>

	<body>


		<div id="tab_bd1">
			<div class="title">
				<div class="left">&nbsp; 
					基础信息<font color="red">（输入订餐人“姓名”或“手机”或“标签”会自动检索出订餐人信息，如果新客户可以直接填写）</font>
				<a  id="cus" class="easyui-linkbutton" iconCls="icon-redo" plain="true" onClick="javascript:loadCustom()">客户信息</a>
					
				</div>
			</div>
			<div class="frame">
				<form  method="post" name="costForm"  id="costForm">
			
			
				<table width="100%" border="0" cellpadding="1" cellspacing="1" bordercolor="#CCCCCC" bgcolor="#CCCCCC" align="center">
					<tr>
						<td class="lbg"  width="15%">
							 订单号：
						<input name="outOrder.orderCode" id="code" type="hidden" value="${outOrder.orderCode}" >
						<input name="outOrder.creator" id="creator" type="hidden"  value="${outOrder.creator}"  >
						<input name="outOrder.createDate" id="createDate" type="hidden" value="${dateString}" >
						<input type="hidden"  name="outOrder.discountFee"   size="35" value="0" id="discount_fee_hid" >
						<input type="hidden"  name="outOrder.customName"   size="35" id="customName" >
							<input type="hidden"  name="outOrder.orderSumFee"   size="35" id="order_sum_fee" >
							<input type="hidden"  name="outOrder.realSumFee"   size="35" id="real_sum_fee" >
							<input type="hidden" name="menuJson" id="menuJson"/>
						
						
						</td>
						<td width="35%">
							<span>${outOrder.orderCode}</span>
						</td>
						<td class="lbg"  width="15%">
							操作人：
						</td>
						<td width="35%">
							<span>${outOrder.creator}</span>
						</td>
					</tr>
					<tr>	
						<td class="lbg"  width="15%">
							操作时间：
						</td>
						<td width="35%">
								<span>${dateString}</span>
						</td>
						<td class="lbg"  width="15%">
							订单状态：
						</td>
						<td width="35%">
							<span>下单</span>
						</td>
					</tr>
					<tr>
						<td class="lbg"  width="15%">
							订餐人：
						</td>
						<td width="35%">
							<input name="outOrder.customId" id="custom_id" type="text"   style="width:330px" >
							<font color="red" size="4">&nbsp;&nbsp;*&nbsp;</font>
								<a id="goon" href="javascript:addCustom()" class="easyui-linkbutton pad" iconCls="icon-search">搜索</a>
							
						</td>
						<td class="lbg"  width="15%">
							订餐人电话：
						</td>
						<td width="35%">
							<input name="outOrder.customPhone" id="custom_phone" type="text" style="width:330px" >
						</td>
					</tr>
					<tr>	
						<td class="lbg"  width="15%">
							订餐人地址：
						</td>
						<td width="35%">
							<input name="outOrder.customAddress" id="custom_address" type="text" style="width:330px"  >
						</td>
						<td class="lbg"  width="15%">
							订餐人备注：
						</td>
						<td width="35%">
							<input name="outOrder.customMemo" id="custom_memo" type="text" style="width:330px" >
						</td>
					</tr>
				</table>
			</div>
		</div>
		
		</form>
			
<!-- 			onclick="confirmDetail()" -->
		<div id="tab_bd1" onclick="confirmDetail()"  >
			<div class="title">
				<span class="left">
					订单明细
				</span>
				<span  style="padding-right:18px;float: right;">
						<a  class="easyui-linkbutton" iconCls="icon-add" plain="true" onClick="javascript:loadDetail()">添加明细</a>
				</span>
			</div>	
				<div class="frame" id="frame1">
					<table class="easyui-datagrid"  id="tt2" data-options="
									height:'auto',
									width:'auto',
									fitColumns:true,
									iconCls: 'icon-edit',
									singleSelect: true,
									url: null,
									method:'get',
									onClickCell: onClickCell
								">
						<thead>
							<tr>
								<th data-options="field:'name',width:250">
									菜品名称
								</th>
								<th data-options="field:'price',width:150">
									单价
								</th>
								<th data-options="field:'num',width:80" >
									数量
								</th>
								<th data-options="field:'sum',width:100">
									金额
								</th>
								<th data-options="field:'oper',width:80,formatter: function(value,row,index){return '<a  href=\'javascript:deletRow('+index+')\'>删除</a>'}">
									操作
								</th>
							</tr>
						</thead>
					</table>
					
					
						<div id="ttDiv" style="height: 24px">
						<a>
						<span style="padding-left:150px;float:left;font-size: 14">
								<span style="font-size: 14;"><font color="red">折扣金额：</font></span>
								<span style="font-size: 14" ><input type="text"  name="outOrder.discount_fee" value="0"  size="35" id="discount_fee" ></span>
							</span>
						
						
							<span style="padding-right:150px;float:right;font-size: 14">
								<span style="font-size: 14">总金额：</span>
								<span style="font-size: 14" id="tt_totalNum">0.000</span>
								<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
								<span style="font-size: 14">金额大写：</span>
								<span style="font-size: 14" id="tt_totalSum">零元整</span>
							</span>
						</a>
					</div>
					
			</div>
			
		</div>
		
			
		<div id="tab_bd1" onclick="confirmDetail()">
			<div class="title">
				<div class="left">
					操作
				</div>
			</div>
			<div class="frame">
				<table width="100%" border="0" cellpadding="1" cellspacing="1" bordercolor="#CCCCCC" bgcolor="#CCCCCC" align="center">
					<tr>
						<td align="center">
							<a id="goon" href="javascript:saveOutOrder()" class="easyui-linkbutton pad" iconCls="icon-ok">确认下单</a>
							<a href="javascript: window.parent.closeTab(); " class="easyui-linkbutton pad"  iconCls="icon-reload">返回</a>
						</td>
				  	</tr>
				</table>
			</div>
		</div>
		
		 <div  id="goodChoeseDiv"  class="easyui-dialog" data-options="title: '菜品选择',   
				    width: 800,
				    height: 550,  
				    top:90, 
				    closed: true,   
				    cache: false,   
				    modal: true  ">
		</div>	
		
		<script type="text/javascript" >
			<!-- 小票打印的js 相关代码-->
			var LODOP;
			function orderPrint(customName,dataJson){
// 				LODOP=getLodop(document.getElementById('LODOP_OB'),document.getElementById('LODOP_EM'));  
// 				LODOP.SET_PRINT_STYLEA(2,"FontSize",12);
// 				LODOP.SET_PRINT_STYLEA(2,"Bold",1);
// 				LODOP.SET_PRINT_PAGESIZE(3,65,50,""); 
// 				LODOP.PRINT_INIT("打印控件功能演示_Lodop功能_按网址打印");
// 				LODOP.ADD_PRINT_URL(5,0,65,130,"detail");
// 				LODOP.SET_PRINT_STYLEA(0,"HOrient",3);
// 				LODOP.SET_PRINT_STYLEA(0,"VOrient",3);
// 				LODOP.PREVIEW();

				MyPreview(customName,dataJson)
				
			}
			
			
			function MyPreview(customName,dataJson) {	
				AddTitle();
				var iCurLine=110;//标题行之后的数据从位置80px开始打印
				
				for(var i in dataJson){
					LODOP.ADD_PRINT_TEXT(iCurLine,2,100,20,dataJson[i].name);
					LODOP.ADD_PRINT_TEXT(iCurLine,104,35,20,dataJson[i].num);
					LODOP.ADD_PRINT_TEXT(iCurLine,141,64,20,dataJson[i].sum);
					iCurLine=iCurLine+15;//每行占25px
					
				}
				
				LODOP.ADD_PRINT_LINE(iCurLine,0,iCurLine,510,0,1);
				
				LODOP.ADD_PRINT_TEXT(iCurLine+5,2,105,20,"总金额："+$("#order_sum_fee").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(iCurLine+5,108,105,20,"折扣金额："+$("#discount_fee_hid").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(iCurLine+20,2,191,20,"实际金额："+$("#real_sum_fee").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				
				LODOP.ADD_PRINT_LINE(iCurLine+38,0,iCurLine+38,510,0,1);
				
				LODOP.ADD_PRINT_TEXT(iCurLine+40,2,189,20,"客户："+customName);
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(iCurLine+55,2,191,20,"手机号："+$("#custom_phone").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(iCurLine+70,2,191,20,"地址："+$("#custom_address").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				
				LODOP.SET_PRINT_PAGESIZE(3,650,60,"");//这里3表示纵向打印且纸高“按内容的高度”；1385表示纸宽138.5mm；45表示页底空白4.5mm
				//LODOP.PREVIEW();		
				LODOP.PRINT();
			};
			
			function AddTitle(){	
				LODOP=getLodop(document.getElementById('LODOP_OB'),document.getElementById('LODOP_EM'));  
				LODOP.PRINT_INITA(0,0,760,321,"打印控件功能演示_Lodop功能_在线编辑获得程序代码");
				LODOP.ADD_PRINT_TEXT(10,32,141,30,"襄阳旅运租车餐馆\n");
				LODOP.SET_PRINT_STYLEA(0,"FontSize",11);
				LODOP.SET_PRINT_STYLEA(0,"LineSpacing",2);
				LODOP.ADD_PRINT_TEXT(42,2,189,20,"单号："+$("#code").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(56,2,191,20,"收银员："+$("#creator").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(71,2,191,20,"操作时间："+$("#createDate").val());
				LODOP.SET_PRINT_STYLEA(0,"FontSize",7);
				LODOP.ADD_PRINT_TEXT(90,2,100,20,"菜名");
				LODOP.SET_PRINT_STYLEA(0,"FontSize",8);
				LODOP.ADD_PRINT_TEXT(90,104,35,20,"数量");
				LODOP.SET_PRINT_STYLEA(0,"FontSize",8);
				LODOP.ADD_PRINT_TEXT(90,141,64,20,"总价");
				LODOP.SET_PRINT_STYLEA(0,"FontSize",8);
				LODOP.ADD_PRINT_LINE(104,2,104,510,0,1);

			};	
			
		</script>
</html>

